package com.zt.weibo.service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import android.content.Context;

import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;
import com.zt.weibo.WeiboApp;
import com.zt.weibo.interfaces.IWeiboServiceListener;
import com.zt.weibo.utils.PrintLog;

/**
 * 提供通过后台线程获取微博数据的方法。
 * @author zhaotong
 */
public class WeiboService
{
	private static WeiboService instance = null;
	private Weibo mWeibo = null;
	private Context mContext = null;
	private ExecutorService mThread = null;
	
	public static WeiboService getInstance(Weibo weibo, Context con)
	{
		if(null == instance)
		{
			instance = new WeiboService(weibo, con);
		}
		return instance;
	}
	
	private WeiboService(Weibo weibo, Context con)
	{
		mWeibo = weibo;
		mContext = con;
		mThread = Executors.newFixedThreadPool(3);
	}
	
	/**
	 * 获取微博（20条）。
	 * @param sinceId 微博ID
	 * @param bIsWantNewer 需要晚于sinceId还是早于sinceId。
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void getStatus(String sinceId, IWeiboServiceListener listener, boolean bIsWantNewer)
	{
    	String url = Weibo.SERVER + "statuses/home_timeline.json";
    	WeiboParameters bundle = new WeiboParameters();
    	bundle.add("access_token", mWeibo.getAccessToken().getToken());
    	bundle.add("count", 20 + "");
    	if(bIsWantNewer)
    	{
    		bundle.add("since_id", sinceId);
    	}
    	else
    	{
    		bundle.add("max_id", sinceId);
    	}
    	mThread.submit(new WeiboTask(mContext, url, bundle, "GET", listener));
	}
	
	/**
	 * 获取指定ID对应的微博信息
	 * @param strId 微博ID
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void getStatusById(String strId, IWeiboServiceListener listener)
	{
		String url = Weibo.SERVER + "statuses/show.json";
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("access_token", mWeibo.getAccessToken().getToken());
		bundle.add("id", strId);
		mThread.submit(new WeiboTask(mContext, url, bundle, "GET", listener));
	}
	
	/**
	 * 发表文字微博
	 * @param content 文字
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void sentStatus(String content, IWeiboServiceListener listener)
	{
    	String url = Weibo.SERVER + "statuses/update.json";
    	WeiboParameters bundle = new WeiboParameters();
    	bundle.add("access_token", mWeibo.getAccessToken().getToken());
		bundle.add("status", content);
    	mThread.submit(new WeiboTask(mContext, url, bundle, "POST", listener));
	}
	

	/**
	 * 转发微博
	 * @param strId 被转发的微博ID
	 * @param content 转发时写下的文字，空就是“转发微博”
	 * @param iIsComment 是否同时评论。0：不评论，1：评论给当前微博，2：评论给原微博，3：都评论。
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void repostStatus(String strId, String content, int iIsComment, 
			IWeiboServiceListener listener)
	{
    	String url = Weibo.SERVER + "statuses/repost.json";
    	WeiboParameters bundle = new WeiboParameters();
    	bundle.add("access_token", mWeibo.getAccessToken().getToken());
    	bundle.add("id", strId);
		bundle.add("is_comment", iIsComment + "");
		if("".equals(content) || 1 == content.indexOf("/"))
		{
			bundle.add("status", "转发微博" + content);
		}
		else
		{
			bundle.add("status", content);
		}
    	mThread.submit(new WeiboTask(mContext, url, bundle, "POST", listener));
	}
	
	/**根据微博ID获取其评论
	 * @param strId 微博ID
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void getComment(String strId, IWeiboServiceListener listener)
	{
		String url = Weibo.SERVER + "comments/show.json";
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("access_token", mWeibo.getAccessToken().getToken());
		bundle.add("id", strId);
		mThread.submit(new WeiboTask(mContext, url, bundle, "GET", listener));
	}
	
	/**
	 * 评论微博
	 * @param strId 要评论的微博ID
	 * @param content 评论内容
	 * @param iIsCommentOri 评论转发微博时，是否也评论到原微博。0：否，1：是。
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void commentStatus(String strId, String content, int iIsCommentOri, 
			IWeiboServiceListener listener)
	{
    	String url = Weibo.SERVER + "comments/create.json";
    	WeiboParameters bundle = new WeiboParameters();
    	bundle.add("access_token", mWeibo.getAccessToken().getToken());
    	bundle.add("id", strId);
		bundle.add("comment_ori", iIsCommentOri + "");
		bundle.add("comment", content);
    	mThread.submit(new WeiboTask(mContext, url, bundle, "POST", listener));
	}
	
	/**
	 * 回复某条微博中的某条评论。
	 * @param strCId 评论ID
	 * @param strId 被评论的微博ID
	 * @param content 回复内容
	 * @param iIsCommentOri 评论转发微博时，是否也评论到原微博。0：否，1：是。
	 * @param listener 回调接口，用于取API接口返回的JSON字符串
	 */
	public void replyComment(String strCId, String strId, String content, int iIsCommentOri,
			IWeiboServiceListener listener)
	{
		String url = Weibo.SERVER + "comments/reply.json";
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("access_token", mWeibo.getAccessToken().getToken());
		bundle.add("cid", strCId);
		bundle.add("id", strId);
		bundle.add("comment", content);
		bundle.add("comment_ori", iIsCommentOri + "");
		mThread.submit(new WeiboTask(mContext, url, bundle, "POST", listener));
	}
	
	/**
	 * 后台线程执行的调用微博API的任务。实现了Runnable接口。
	 * @author zhaotong
	 */
	private class WeiboTask implements Runnable
	{
		private Context mContext = null;
		private String url = "";
		private WeiboParameters bundle = null;
		private IWeiboServiceListener listener = null;
		private String method = "";
		
		/**
		 * 构造新任务
		 * @param mContext
		 * @param url 接口相应url
		 * @param bundle 接口相应参数
		 * @param method 接口使用POST或是GET
		 * @param listener 回调接口
		 */
		public WeiboTask(Context mContext, String url, WeiboParameters bundle, String method,
				IWeiboServiceListener listener)
		{
			this.mContext =mContext;
			this.url = url;
			this.bundle = bundle;
			this.listener = listener;
			this.method = method;
		}
		
		@Override
		public void run()
		{
			final StringBuffer strJson = new StringBuffer();
			try
			{
				WeiboApp.mHandler.post(new Runnable() {
					
					@Override
					public void run()
					{
						if(null != listener)
						{
							listener.onStart();
						}
					}
				});
				String str = mWeibo.request(mContext, url, bundle, 
						method, mWeibo.getAccessToken());
				strJson.append(str);
				PrintLog.debug(strJson.toString());
				WeiboApp.mHandler.post(new Runnable() {
					
					@Override
					public void run()
					{
						if(null != listener)
						{
							listener.onCompl(strJson.toString());
						}
					}
				});
			}
			catch (WeiboException e)
			{
				PrintLog.debug(e.getMessage() + "错误码" + e.getStatusCode());
				strJson.append("error = " + e.getStatusCode());
				WeiboApp.mHandler.post(new Runnable() {
					
					@Override
					public void run()
					{
						if(null != listener)
						{
							listener.onError(strJson.toString());
						}
					}
				});
			}
		}
	}
	
}
